﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MappingFactory.NHUtils;
using System.ComponentModel;
using System.Reflection;
using Remotion.Linq.Collections;

namespace MappingFactory
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// BlackMofo.DAL.dll中将要产生映射的所有类
        /// </summary>
        private List<MapperItem> AllMappers = new List<MapperItem>();

        /// <summary>
        /// 当前显示的BlackMofo.DAL.dll中将要产生映射的类
        /// </summary>
        public ObservableCollection<MapperItem> MapperItems
        {
            get { return (ObservableCollection<MapperItem>)GetValue(MapperItemsProperty); }
            set { SetValue(MapperItemsProperty, value); }
        }
        public static readonly DependencyProperty MapperItemsProperty =
            DependencyProperty.Register("MapperItems", typeof(ObservableCollection<MapperItem>), typeof(MainWindow), new UIPropertyMetadata(new ObservableCollection<MapperItem>()));

        /// <summary>
        /// 无参构造
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            //初始化动态库（BlackMofo.DAL.dll）路径
            if (!System.IO.File.Exists(assemblyAddress))
            {
                assemblyAddress = System.IO.Path.Combine(Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("MappingFactory")), @"DAL\bin\Release\BlackMofo.DAL.dll");
            }

            //加载BlackMofo.DAL.dll的类
            Type[] types = Assembly.LoadFile(assemblyAddress).GetExportedTypes();
            types = types.Where(x => { return x.Name.EndsWith("Mapper"); }).ToArray();
            AllMappers.Clear();
            foreach (Type item in types)
            {
                MapperItem newMI = new MapperItem();
                newMI.Name = item.Name;
                newMI.FullName = item.FullName;
                newMI.IsSelected = false;
                AllMappers.Add(newMI);
            }
            foreach (var item in AllMappers)
            {
                MapperItems.Add(item);
            }
            //MapperItems.AddRange(AllMappers);
        }

        /// <summary>
        /// xml文件存放位置
        /// </summary>
        private string outXmlFilePath = System.IO.Path.Combine(Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("MappingFactory")), @"DAL\MappingFiles\");
        /// <summary>
        /// 动态库（BlackMofo.DAL.dll）路径
        /// </summary>
        private string assemblyAddress = System.IO.Path.Combine(Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("MappingFactory")), @"DAL\bin\Debug\BlackMofo.DAL.dll");

        /// <summary>
        /// 生成映射文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGenerateMappingFiles_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!System.IO.File.Exists(assemblyAddress))
                { MessageBox.Show("无法找到DAL.dll"); }
                if (!System.IO.Directory.Exists(outXmlFilePath))
                { MessageBox.Show("无法找到输出目录"); }
                this.tbCurStatus.Text = "正在生成映射文件...";
                //List<MapperItem> tmpList = MapperItems.Where(x => x.IsSelected).ToList();
                //if (tmpList.Count <= 0)
                //{ this.tbCurStatus.Text = "没有选中任何类"; return; }
                //NHBusinessBuilder bb = new NHBusinessBuilder(assemblyAddress, outXmlFilePath, tmpList);
                NHBusinessBuilder bb = new NHBusinessBuilder(assemblyAddress, outXmlFilePath);
                bb.BuildMappingFile();
                this.tbCurStatus.Text = "生成映射文件.hbm.xml成功！";
            }
            catch (Exception ex)
            {
                this.tbCurStatus.Text = "生成映射文件hbm.xml失败！\n错误信息：" + ex.Message;
            }
        }

        /// <summary>
        /// 生成数据表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGenerateTables_Click(object sender, RoutedEventArgs e)
        {
            //(sender as Button).Content = (typeof(long) == typeof(Int64));
            //if (typeof(int) != typeof(long))
            //{
            //    return;
            //}

            if (MessageBox.Show("是否确认生成表结构", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
            {
                this.tbCurStatus.Text = "用户取消";
                return;
            }

            try
            {
                this.tbCurStatus.Text = "正在生成库表结构...";
                //List<MapperItem> tmpList = MapperItems.Where(x => x.IsSelected).ToList();
                //if (tmpList.Count <= 0)
                //{ this.tbCurStatus.Text = "没有选中任何类"; return; }
                //NHBusinessBuilder bb = new NHBusinessBuilder(assemblyAddress, outXmlFilePath, tmpList);
                NHBusinessBuilder bb = new NHBusinessBuilder(assemblyAddress, outXmlFilePath);
                bb.BuildDBSchema();
                this.tbCurStatus.Text = "生成库表结构成功！";
            }
            catch (Exception ex)
            {
                this.tbCurStatus.Text = "生成库表结构失败！\n错误信息：\n" + ex.Message;
            }
        }

        /// <summary>
        /// 全部设置为未选中
        /// </summary>
        private void UnSelect()
        {
            foreach (MapperItem item in AllMappers)
            { item.IsSelected = false; }
        }

        /// <summary>
        /// 筛选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            UnSelect();
            MapperItems.Clear();
            foreach (var item in AllMappers.Where(x => { return x.Name.Contains(this.txtName.Text); }))
            {
                MapperItems.Add(item);
            }
            //MapperItems.AddRange();
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            UnSelect();
            MapperItems.Clear();
            foreach (var item in AllMappers)
            {
                MapperItems.Add(item);
            }
            //MapperItems.AddRange();
        }

        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSelectAll_Click(object sender, RoutedEventArgs e)
        {
            foreach (MapperItem item in MapperItems)
            {
                item.IsSelected = chkSelectAll.IsChecked.Value;
            }
        }
    }
    public class MapperItem : INotifyPropertyChanged
    {
        private string _Name = "";
        public string Name
        {
            get { return _Name; }
            set
            {
                if (value != _Name)
                {
                    _Name = value;
                    this.PropertyNotifyChanged("Name");
                }
            }
        }

        private string _FullName = "";
        public string FullName
        {
            get { return _FullName; }
            set
            {
                if (value != _FullName)
                {
                    _FullName = value;
                    this.PropertyNotifyChanged("FullName");
                }
            }
        }

        private bool _IsSelected = false;
        public bool IsSelected
        {
            get { return _IsSelected; }
            set
            {
                if (value != _IsSelected)
                {
                    _IsSelected = value;
                    this.PropertyNotifyChanged("IsSelected");
                }
            }
        }

        #region 实现接口
        public event PropertyChangedEventHandler PropertyChanged;
        protected void PropertyNotifyChanged(string propName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
        #endregion //实现接口
    }
}
